package com.hotacorp.opencloud.userservice.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotacorp.opencloud.userservice.dao.SysRoleMenuDao;
import com.hotacorp.opencloud.userservice.entity.SysRoleMenuEntity;
import com.hotacorp.opencloud.userservice.service.SysRoleMenuService;

/**
 * 角色权限管理接口实现
 * @author lwg
 *
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenuEntity> implements SysRoleMenuService {

	@Override
	public void saveOrUpdate(Long roleId, List<Long> menuIdList, Long tenantid) {
		//先删除角色与菜单关系
		removeRoles(Arrays.asList(roleId), tenantid);

		if(menuIdList.size() == 0){
			return ;
		}

		//保存角色与菜单关系
		for(Long menuId : menuIdList){
			SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
			sysRoleMenuEntity.setMenuId(menuId);
			sysRoleMenuEntity.setRoleId(roleId);
			sysRoleMenuEntity.setTenantid(tenantid);

			this.save(sysRoleMenuEntity);
		}
	}

	@Override
	public List<Long> queryMenuIdList(Long roleId, Long tenantid) {
		List<SysRoleMenuEntity> rrrEntities = baseMapper.selectList((new QueryWrapper<SysRoleMenuEntity>()).eq("tenantid", tenantid).eq("role_id", roleId));
		Set<Long> yyyy = rrrEntities.stream().map(entity->{return entity.getMenuId();}).collect(Collectors.toSet());
		return yyyy.stream().collect(Collectors.toList());
	}

	@Override
	public void removeRoles(List<Long> roleList, Long tenantid) {
		baseMapper.delete((new QueryWrapper<SysRoleMenuEntity>()).eq("tenantid", tenantid).in("role_id", roleList));
	}

}